//
//  JCEditClubInformationVC.m
//  SquashSpark
//
//  Created by 郭吉成 on 2017/12/6.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "JCEditClubInformationVC.h"
#import "JCClubApi.h"
#import "SystemSelectPhotoManager.h"
#import <Qiniu/QiniuSDK.h>
#import "YFAlertHelper.h"
#import "JCChoiseImageView.h"
#import "YFMomentApi.h"
#import "UIImage+HXExtension.h"
#import "JCClubModel.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import "ClubsSetting.h"

#define     kInputViewMinHeight     28

@interface JCEditClubInformationVC ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *backImageView;
@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;

@property (weak, nonatomic) IBOutlet UITextView *clubNameInput;
@property (weak, nonatomic) IBOutlet UIView *clubNameLine;
@property (weak, nonatomic) IBOutlet UITextView *clubAddressInput;
@property (weak, nonatomic) IBOutlet UIView *clubAddressLine;
@property (weak, nonatomic) IBOutlet UITextView *clubIntroductionInput;
@property (weak, nonatomic) IBOutlet UIView *clubIntroductionLine;
@property (weak, nonatomic) IBOutlet UILabel *clubIntroductionLabel;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIView *showView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *nameInputHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addressInputHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *introdutionInputHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *showViewContentHeight;
@property (strong, nonatomic) UITextView *currentTextView;
@property (assign, nonatomic) CGFloat offsetY;
@property (assign, nonatomic) CGFloat keyBoardHeight;

@property (strong, nonatomic) UIBarButtonItem *saveItem;

@property (strong, nonatomic) SystemSelectPhotoManager *photoManger;
@property (strong, nonatomic) UIImage *headerImage;
@property (strong, nonatomic) UIImage *coverImage;
@property (strong, nonatomic) NSArray *images;
@property (strong, nonatomic) NSString *headerURL;
@property (strong, nonatomic) NSString *coverURL;
@property (strong, nonatomic) JCClubModel *clubModel;

@end

@implementation JCEditClubInformationVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initCode];
    [self loadData];
}

- (void)loadData{
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [JCClubApi getClubInfoWithClubID:_clubID complete:^(NSError *error, JCClubModel *clubInfo) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [weakSelf.hud dismiss];
            weakSelf.clubModel = clubInfo;
            [weakSelf.backImageView sd_setImageWithURL:clubInfo.banner placeholderImage:kPlaceholdImage];
            [weakSelf.headerImageView sd_setImageWithURL:clubInfo.headIcon placeholderImage:kPlaceholdImage];
            weakSelf.clubNameInput.text = clubInfo.name;
            weakSelf.clubAddressInput.text = clubInfo.address;
            weakSelf.clubIntroductionInput.text = clubInfo.describe;
        }
    }];
}

- (void)initCode{
    _scrollView.alwaysBounceVertical = YES;
    self.navigationItem.title = @"Club Information";
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    _saveItem = [[UIBarButtonItem alloc] initWithTitle:@"Save"
                                                 style:UIBarButtonItemStyleDone
                                                target:self
                                                action:@selector(saveAction:)];
    _saveItem.enabled = NO;
    self.navigationItem.rightBarButtonItem = _saveItem;
}

- (void)saveAction:(UIBarButtonItem *)sender{
    __weak typeof(self)weakSelf = self;
    [self.hud showWithMaskType:WSProgressHUDMaskTypeClear];
    [self uploadImagesQNComplated:^(NSArray *imageUrlArr, NSError *error) {
        if (error) {
            [weakSelf.hud dismiss];
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            NSString *headerString = [NSString stringWithContentsOfURL:weakSelf.clubModel.headIcon encoding:NSUTF8StringEncoding error:nil];
            NSString *coverString = [NSString stringWithContentsOfURL:weakSelf.clubModel.banner encoding:NSUTF8StringEncoding error:nil];
            if (imageUrlArr.count == 2) {
                headerString = imageUrlArr.firstObject;
                coverString = imageUrlArr.lastObject;
            }else if(imageUrlArr.count == 1){
                if (weakSelf.headerImage) {
                    headerString = imageUrlArr.firstObject;
                }else{
                    coverString = imageUrlArr.firstObject;
                }
            }
            [JCClubApi editClubWithClubID:weakSelf.clubID
                                     name:weakSelf.clubModel.name
                                headerURL:headerString
                                 coverURL:coverString
                                  address:weakSelf.clubModel.address
                                 describe:weakSelf.clubModel.describe
                                 complete:^(NSError *error) {
                                     if (error) {
                                         [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
                                     }else{
                                         [weakSelf.hud showSuccessWithStatus:@"Success" dimissAfterSecond:2];
                                         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                             [weakSelf.navigationController popViewControllerAnimated:YES];
                                         });
                                     }
                                 }];
        }
    }];
}


- (void)keyboardWillShow:(NSNotification *)notification{
    
    NSDictionary *userInfo = [notification userInfo];
    NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [value CGRectValue];
    _keyBoardHeight = keyboardRect.size.height - 40;
    
    CGFloat valueY = 0;
    if (_currentTextView == _clubNameInput) {
        if ([_currentTextView.text isEqualToString:@"Club Name"]) {
            _currentTextView.text = @"";
        }
        valueY = _clubNameLine.frame.origin.y;
    }else if (_currentTextView == _clubAddressInput){
        if ([_currentTextView.text isEqualToString:@"Club Address"]) {
            _currentTextView.text = @"";
        }
        valueY = _clubAddressLine.frame.origin.y;
    }else if (_currentTextView == _clubIntroductionInput){
        if ([_currentTextView.text isEqualToString:@"Club Introduction"]) {
            _currentTextView.text = @"";
        }
        valueY = _clubIntroductionLabel.frame.origin.y;
    }
    _offsetY = valueY - _keyBoardHeight;
//    _lastOffsetY = _scrollView.contentOffset.y;
    [_scrollView setContentOffset:CGPointMake(0, _offsetY) animated:YES];
}

- (void)keyboardWillHide:(NSNotification *)notification{
    if (_currentTextView == _clubNameInput) {
        if ([_currentTextView.text isEqualToString:@""]) {
            _currentTextView.text = @"Club Name";
        }
    }else if (_currentTextView == _clubAddressInput){
        if ([_currentTextView.text isEqualToString:@""]) {
            _currentTextView.text = @"Club Address";
        }
    }else if (_currentTextView == _clubIntroductionInput){
        if ([_currentTextView.text isEqualToString:@""]) {
            _currentTextView.text = @"Club Introduction";
        }
    }
    [_scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
}

#pragma mark -- UITextView代理
- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    _currentTextView = textView;
    return YES;
}
- (BOOL)textViewShouldEndEditing:(UITextView *)textView{
    return YES;
}
- (void)textViewDidChange:(UITextView *)textView{
    
    if (textView == _clubNameInput) {
        _clubModel.name = textView.text;
    }else if (textView == _clubAddressInput){
        _clubModel.address = textView.text;
    }else if (textView == _clubIntroductionInput){
        _clubModel.describe = textView.text;
        _clubIntroductionLabel.text = [NSString stringWithFormat:@"%ld/300",_clubIntroductionInput.text.length];
    }
    if (_clubModel.name.length > 0 &&
        _clubModel.address.length > 0 &&
        _clubModel.describe.length > 0) {
        _saveItem.enabled = YES;
    }else{
        _saveItem.enabled = NO;
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    if ([text isEqualToString:@"\n"]) {
        [self.view endEditing:YES];
        return NO;
    }
    BOOL result = YES;
    NSString *inputString = [textView.text stringByAppendingString:text];
    UITextView *vv = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth - 30, 0)];
    vv.textColor = [UIColor whiteColor];
    vv.font = kOpenSansFont(OpenSansRegular, 16);
    vv.text = inputString;
    [vv sizeToFit];
    CGFloat height = vv.bounds.size.height;
    
    if (textView == _clubNameInput) {
        if (inputString.length > 30) {
            result = NO;
        }
        _nameInputHeight.constant = MAX(height, kInputViewMinHeight);
    }else if (textView == _clubAddressInput){
        if (inputString.length > 100) {
            result = NO;
        }
        _addressInputHeight.constant = MAX(height, kInputViewMinHeight);
    }else if (textView == _clubIntroductionInput){
        if (inputString.length > 300) {
            result = NO;
        }
        _introdutionInputHeight.constant = MAX(height, kInputViewMinHeight);
    }
    _showViewContentHeight.constant = 466+(_nameInputHeight.constant + _addressInputHeight.constant + _introdutionInputHeight.constant);
    [UIView animateWithDuration:.3 animations:^{
        [self.view layoutIfNeeded];
        CGFloat valueY = 0;
        if (textView == _clubNameInput) {
            valueY = _clubNameLine.frame.origin.y;
        }else if (textView == _clubAddressInput){
            valueY = _clubAddressLine.frame.origin.y;
        }else if (textView == _clubIntroductionInput){
            valueY = _clubIntroductionLine.frame.origin.y;
        }
        _offsetY = valueY - _keyBoardHeight;
        [_scrollView setContentOffset:CGPointMake(0, _offsetY) animated:NO];
    } completion:^(BOOL finished) {
        
    }];
    return result;
}

- (IBAction)editHeaderImageAction:(id)sender {
    __weak typeof(self)weakSelf = self;
    JCChoiseImageView *view =  [[UINib nibWithNibName:@"JCChoiseImageView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil].firstObject;
    PopupViewController *alert = [YFAlertHelper showPresentInView:nil alertView:view withAlertViewFrame:CGRectMake(0, 0, 280, 130) animationType:DetailViewControllerPresentAnimationTypeUp tapMaskViewDismiss:YES];
    __weak typeof(alert)weakAlert = alert;
    view.takePhotoHandle = ^{
        [weakSelf selectImage:ImageChoiseTypeHeader isTakePhoto:YES];
        [weakAlert dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
    };
    view.LibraryPhotoHandle = ^{
        [weakSelf selectImage:ImageChoiseTypeHeader isTakePhoto:NO];
        [weakAlert dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
    };
}

- (IBAction)editBackImageAction:(UITapGestureRecognizer *)sender {
    __weak typeof(self)weakSelf = self;
    JCChoiseImageView *view =  [[UINib nibWithNibName:@"JCChoiseImageView" bundle:[NSBundle mainBundle]] instantiateWithOwner:self options:nil].firstObject;
    PopupViewController *alert = [YFAlertHelper showPresentInView:nil alertView:view withAlertViewFrame:CGRectMake(0, 0, 280, 130) animationType:DetailViewControllerPresentAnimationTypeUp tapMaskViewDismiss:YES];
    __weak typeof(alert)weakAlert = alert;
    view.takePhotoHandle = ^{
        [weakSelf selectImage:ImageChoiseTypeCover isTakePhoto:YES];
        [weakAlert dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
    };
    view.LibraryPhotoHandle = ^{
        [weakSelf selectImage:ImageChoiseTypeCover isTakePhoto:NO];
        [weakAlert dismissFromParentViewControllerWithAnimationType:DetailViewControllerAnimationTypeSlide];
    };
}

- (void)selectImage:(ImageChoiseType)type isTakePhoto:(BOOL)isTakePhoto{
    __weak typeof(self)weakSelf = self;
    SystemSelectPhotoManager *photoManger = [SystemSelectPhotoManager selectPhotoManagerWithEditCaseType:kSystemDeflaut];
    self.photoManger = photoManger;
    [photoManger takePhotoBySource:!isTakePhoto canEdit:YES parentViewController:self selectCallBlock:^(UIImage *selectImage, NSError *error) {
        if (error) {
            [weakSelf.hud showErrorWithString:error.domain dimissAfterSecond:2];
        }else{
            weakSelf.saveItem.enabled = YES;
            if (type == ImageChoiseTypeHeader) {
        
                weakSelf.headerImage = selectImage;
                weakSelf.headerImageView.image = selectImage;
            }else if (type == ImageChoiseTypeCover){
            
                weakSelf.coverImage = selectImage;
                weakSelf.backImageView.image = selectImage;
            }
        }
    }];
}

- (void)uploadImagesQNComplated:(void(^)(NSArray *imageUrlArr,NSError *error))completedBlock {
    
    __weak typeof(self) weakSelf = self;
    if (!_headerImage && !_coverImage) {
        completedBlock(nil,nil);
        return;
    }
    [[YFNetworkingService sharedInstance] sendRequest:[YFMomentApi requestApiWithType:kGetQiNiuUploadImageToMomentApi andParam:nil] callback:^(BOOL success, id result, NSError *error) {
        if (success == NO) {
            if (completedBlock) {
                completedBlock(nil,[NSError errorWithDomain:@"获取七牛token失败" code:-1001 userInfo:nil]);
            }
            return;
        }else {
            NSString *token = [[result responseInfo] objectForKey:@"token"];
            QNUploadOption *option = [[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
                //                [weakSelf.hud showProgress:percent];
            }];
    
            if (weakSelf.headerImage && weakSelf.coverImage) {
                weakSelf.images = @[weakSelf.headerImage, weakSelf.coverImage];
            }else if (_headerImage && !weakSelf.coverImage){
                weakSelf.images = @[weakSelf.headerImage];
            }else if (!weakSelf.headerImage && weakSelf.coverImage){
                weakSelf.images = @[weakSelf.coverImage];
            }
            [weakSelf upladToQNImages:weakSelf.images
                              atIndex:0
                                token:token
                                 keys:[NSMutableArray array]
                         filenamesArr:[NSMutableArray arrayWithCapacity:weakSelf.images.count]
                               option:option
                            completed:^(BOOL success, NSMutableArray *fileNameArr) {
                                
                                if (success) {
                                    if (fileNameArr.count == weakSelf.images.count) {
                                        NSMutableArray *arrM = [NSMutableArray array];
                                        [fileNameArr enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                                            [arrM addObject:[NSString stringWithFormat:@"%@%@",kImageBaseUrl,obj]];
                                        }];
                                        if (completedBlock) {
                                            completedBlock(arrM.copy,nil);
                                        }
                                    }else{
                                        [weakSelf.hud showErrorWithString:@"上传出错，请重试" dimissAfterSecond:2];
                                    }
                                }else {
                                    if (completedBlock) {
                                        completedBlock(nil,[NSError errorWithDomain:NSLocalizedString(@"Upload picture failed", @"上传图片失败") code:-1002 userInfo:nil]);
                                    }
                                }
                                
            }];
        }
    }];
}

- (void)upladToQNImages:(NSArray <UIImage *>*)images
                atIndex:(NSInteger)index
                  token:(NSString *)token
                   keys:(NSMutableArray *)keys
           filenamesArr:(NSMutableArray *)filenamesArr
                 option:(QNUploadOption *)option
              completed:(void(^)(BOOL success,NSMutableArray *fileNameArr))completedBlock {
    
    UIImage *image = images[index];
    __block NSInteger imageIndex = index;
    NSData *data = [image compressToDataHX];
    NSTimeInterval time= [[NSDate date] timeIntervalSince1970];
    //拼接图片上传后的路径： http://staticapp.coollang.com/bq/club/+ uuid + 下划线 + 时间戳 + 下划线 + 序号 + 中划线 + 图片宽*图片高 + .jpg
    NSString *filename = [NSString stringWithFormat:@"bq/club/%@_%.f_%ld-%d*%d.%@",[User getLastUser].userID,time,(long)imageIndex,(int)image.size.width,(int)image.size.height,@"jpg"];
    [filenamesArr addObject:filename];
    
    [[YFNetworkingService qNUploadManager] putData:data
                                               key:filename
                                             token:token
                                          complete:^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
        if (info.isOK) {
            [keys addObject:key];
//            YFLog(@" --- idInex %ld,OK",(long)index);
            imageIndex++;
//            YFLog(@" --上传完成,%@",filename);
//            for (NSString *imgKey in keys) {
//                NSLog(@"%@",imgKey);
//            }
            if (imageIndex == images.count) {
                if (completedBlock) {
                    completedBlock(YES,filenamesArr);
                }
            }
            else{
                [self upladToQNImages:images atIndex:imageIndex token:token keys:keys filenamesArr:filenamesArr option:option completed:completedBlock];
            }
        }else{
            if (completedBlock) {
                completedBlock(NO,nil);
            }
            YFLog(@"上传失败,%@",filename);
        }
    } option:option];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
